package com.coze.lg.cozeagent.service.serviceImpl;

import com.coze.lg.cozeagent.service.CozeService;
import com.coze.openapi.client.chat.CreateChatReq;
import com.coze.openapi.client.chat.model.ChatEvent;
import com.coze.openapi.client.chat.model.ChatEventType;
import com.coze.openapi.client.connversations.message.model.Message;
import com.coze.openapi.service.service.CozeAPI;
import io.reactivex.Flowable;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@Service
public class CozeServiceImpl implements CozeService {
    private final CozeAPI cozeAPI;
    String userID = "123";
    public CozeServiceImpl(CozeAPI cozeAPI) {
        this.cozeAPI = cozeAPI;
    }

    @Override
    public String chat(String message, String botID) {
        CreateChatReq req =
                CreateChatReq.builder()
                        .botID(botID)
                        .userID(userID)
                        .messages(Collections.singletonList(Message.buildUserQuestionText("What can you do?")))
                        .build();
        StringBuilder fullResponse = new StringBuilder();
        Flowable<ChatEvent> resp = cozeAPI.chat().stream(req);
        resp.blockingForEach(
                event -> {
                    if (ChatEventType.CONVERSATION_MESSAGE_DELTA.equals(event.getEvent())) {
                        String content = event.getMessage().getContent();
                        fullResponse.append(content);
                        System.out.print(content);
                    }
                    if (ChatEventType.CONVERSATION_CHAT_COMPLETED.equals(event.getEvent())) {
                        System.out.println("\nToken usage: " + event.getChat().getUsage().getTokenCount());
                    }
                });
        System.out.println("done");
        cozeAPI.shutdownExecutor();
        return fullResponse.toString();
    }
}
